//
//  NetworkTool.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/8.
//  Copyright © 2015年 hzj. All rights reserved.
//



import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}

class NetworkTool: AFHTTPSessionManager {
    
    //单例
//    static let sharedTool = NetworkTool()
    static let sharedTool:NetworkTool = {
        var instance = NetworkTool(baseURL: nil)
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    

    //发送网络请求
   private func request(method: RequestMethod, URLString: String,var parameters: [String: AnyObject]?,haveToken:Bool = true) -> RACSignal {
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            if haveToken {
                guard let token = UserAccountViewModel.sharedUserAccountViewModel.access_token else{
                    
                    subscriber.sendError(NSError(domain: "com.asdf.error", code: -1233, userInfo: ["errormessage" : "token为空"]))
                    return nil
                }
                
                if parameters == nil{
                    parameters = [String:AnyObject]()
                }
                parameters!["access_token"] = token
                
            }
            
            //成功时的回调闭包
            let successCallBack = {(task:NSURLSessionDataTask,result:AnyObject) ->Void in
                
                subscriber.sendNext(result)
                subscriber.sendCompleted()
                
            }
            //失败时的回调闭包
            let failureCallBack = {(task:NSURLSessionDataTask,error:NSError) ->Void in
                
                subscriber.sendError(error)
            }
            
            if method == .GET{
                self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
                
            }else{
                self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }

            return nil
        })
    }
    //MARK:-获取token的方法
    func loadTheToken(code:String)->RACSignal{
        
        let URLString = "https://api.weibo.com/oauth2/access_token"

        let parameters = ["client_id": clientID,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectURL]
        /*
        //打印出的结果可观测出其类型
        responseSerializer = AFHTTPResponseSerializer()
        POST(URLString, parameters: parameters, success: { (_, result) -> Void in
            print("测试")
            
            let str = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
            printLog(str)
            print("测试")

            }, failure: nil)
         */
        
        return request(.POST, URLString: URLString, parameters: parameters,haveToken: false)
    }

    
    //相关参数
    private let clientID = "929961761"
    private let AppSecret = "9e81d3e6ee7e9433c9e8305048353fdd"
    let redirectURL = "https://www.baidu.com"
    
    //MARK: - 授权页的请求
    var urlString:NSURL{
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(clientID)&redirect_uri=\(redirectURL)"
        return NSURL(string: url)!
    }
    
    
    //MARK:- 据token等信息获得用户信息
    
    func loadTheUserInfo(uid:String) ->RACSignal{
        let urlstring = "https://api.weibo.com/2/users/show.json"
        let parameters = ["uid": uid]
        return request(.GET, URLString: urlstring, parameters: parameters,haveToken: true)
    }
///MARK:- 获取当前登录用户及其所关注用户的最新微博
//    since_id 	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
//    max_id 	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///- see: [https://api.weibo.com/2/statuses/friends_timeline.json](https://api.weibo.com/2/statuses/friends_timeline.json)
    
    
    func loadTheStatus(Since_id since_id:Int,max_id:Int) ->RACSignal{
        var parameters = [String:AnyObject]()
        let urlstring = "https://api.weibo.com/2/statuses/friends_timeline.json"
        if since_id > 0 {
            parameters["since_id"] = since_id
        }else if max_id > 0 {
            //-1是为防止重复max_id
            parameters["max_id"] = max_id - 1
        }
        return request(.GET, URLString: urlstring, parameters: parameters)
    }

}
